﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using OnlineVideos.Data;
using OnlineVideos.Common;
using Common.Library;

using System.ComponentModel;
using Microsoft.Phone.BackgroundAudio;
using System.Windows.Threading;
using Common;
using Common.Utilities;
using System.Windows.Navigation;

using AdRotator;
using OnlineVideos.Entities;
using System.Windows.Controls.Primitives;
using Microsoft.Phone.Shell;
using System.Threading.Tasks;
using PicasaMobileInterface;

namespace OnlineVideos
{
    public partial class CricketDetail : PhoneApplicationPage
    {
        bool appbarvisible = true;
        ListPicker pickr = default(ListPicker);
        Popup pop = new Popup();
        PivotItem currentItem = default(PivotItem);
        public DispatcherTimer storyboardtimer;
        string Stitle = string.Empty;
        string id = string.Empty;
        string Atitle = string.Empty;
        string title = string.Empty;
        string index = string.Empty;
        string secondarytileindex = string.Empty;
        string navigationvalue = string.Empty;
        string pivotindex = string.Empty;
        public CricketDetail()
        {
            try
            {
                InitializeComponent();
                if (!ShowCastManager.ShowGamePivotForCricket(AppSettings.ShowID))
                {
                    pvtMainDetails.Items.Remove(gamepivot);
                }
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in CricketDetail Method In CricketDetail.cs file.", ex);
            }

        }

        public void addgame()
        {
            try
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    if (!ShowCastManager.ShowGameControlForCricket(AppSettings.ShowID))
                    {

                        if (GameGrid.Children.Count > 0)
                            GameGrid.Children.RemoveAt(0);
                        MemoryGame showgame = new MemoryGame();
                        GameGrid.Children.Add(showgame);

                        storyboardtimer = new DispatcherTimer();
                        storyboardtimer.Interval = TimeSpan.FromSeconds(2);
                        storyboardtimer.Tick += new EventHandler(storyboardtimer_Tick);
                        storyboardtimer.Start();
                    }

                });
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in addgame Method In CricketDetail.cs file.", ex);
            }
        }
        private void pvtMainDetails_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int showid = AppSettings.ShowUniqueID;
            try
            {
                currentItem = e.AddedItems[0] as PivotItem;
                if (appbarvisible == true)
                {
                    if (currentItem.Header != null)
                    {

                        if (currentItem.Header.ToString() == "game")
                        {
                            if (this.ApplicationBar.MenuItems.Count == 2)
                                this.ApplicationBar.MenuItems.RemoveAt(1);

                        }
                        else
                        {
                            if (this.ApplicationBar.MenuItems.Count < 2)
                            {
                                ApplicationBarMenuItem appBarMenuitem = null;
                                if (currentItem.Header.ToString() == "videos")
                                    appBarMenuitem = new ApplicationBarMenuItem("Add videos");
                                else if (currentItem.Header.ToString() == "summary")
                                    appBarMenuitem = new ApplicationBarMenuItem("Add summary");
                                else
                                    appBarMenuitem = new ApplicationBarMenuItem("Add image for cast");
                                appBarMenuitem.Click += btnadd_Click_1;
                                this.ApplicationBar.MenuItems.Add(appBarMenuitem);
                            }
                            else
                            {
                                if (currentItem.Header.ToString() == "videos")
                                    ((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).Text = "Add videos";
                                else if (currentItem.Header.ToString() == "summary")
                                    ((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).Text = "Add summary";
                                else
                                    ((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).Text = "Add image for cast";

                            }

                        }
                        if (Constants.connection.Table<MatchBattingScore>().Where(i => i.MatchId == showid).FirstOrDefaultAsync().Result != null)
                        {
                            if (currentItem.Header.ToString() == "summary")
                            {
                                ((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).IsEnabled = false;
                            }
                            else
                                ((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).IsEnabled = true;

                        }
                    }
                }
                if (pvtMainDetails.SelectedIndex == 0)
                {
                    Border frameBorder = (Border)VisualTreeHelper.GetChild(Application.Current.RootVisual, 0);
                    AdRotatorControl Adc = frameBorder.FindName("AdRotatorWin8") as AdRotatorControl;
                    Adc.IsAdRotatorEnabled = false;
                    Adc.Visibility = Visibility.Collapsed;
                }
                else
                {
                    Border frameBorder = (Border)VisualTreeHelper.GetChild(Application.Current.RootVisual, 0);
                    AdRotatorControl Adc = frameBorder.FindName("AdRotatorWin8") as AdRotatorControl;
                    Adc.IsAdRotatorEnabled = true;
                    Adc.Visibility = Visibility.Visible;
                    Adc.Invalidate();
                }

                if (pvtMainDetails.SelectedIndex == 2)
                {
                    BackgroundHelper bwhelper = new BackgroundHelper();
                    bwhelper.AddBackgroundTask(
                    (object s, DoWorkEventArgs a) =>
                    {
                        addgame();
                    },
                    (object s, RunWorkerCompletedEventArgs a) =>
                    {

                    }
                    );

                    bwhelper.RunBackgroundWorkers();

                }
                else
                {
                    if (BackgroundAudioPlayer.Instance.PlayerState == PlayState.Playing)
                    {
                        if (BackgroundAudioPlayer.Instance != null && BackgroundAudioPlayer.Instance.Track.Source.ToString().Contains("Claps.mp3"))
                        {
                            BackgroundAudioPlayer.Instance.Stop();
                        }
                    }
                }
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in pvtMainDetails_SelectionChanged Method In CricketDetail.cs file.", ex);
            }
        }
        void storyboardtimer_Tick(object sender, EventArgs e)
        {
            try
            {
                if (pvtMainDetails.SelectedIndex == 2)
                {
                    if (OnlineVideos.Game.GameInstance.gameopened == false)
                    {
                        foreach (OnlineVideos.Game.MemoryCard m in OnlineVideos.Game.GameInstance.stopstoryboard)
                        {
                            m.storyboardfromx = "3";
                            m.storyboardtox = "-3";
                            m.storyboardfromy = "3";
                            m.storyboardtoy = "-3";
                            m.storyboardfromz = "3";
                            m.storyboardtoz = "-3";
                        }
                        storyboardtimer.Stop();
                    }
                }
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in storyboardtimer_Tick Method In CricketDetail.cs file.", ex);
            }
        }
        private void LoadAds()
        {
            try
            {
                PageHelper.LoadAdControl(LayoutRoot, adstaCast, 1);
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in LoadAds Method In SongDetails file", ex);
                string excepmess = "Exception in LoadAds Method In SongDetails file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
            }

        }
        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                LoadAds();
                FlurryWP8SDK.Api.LogEvent("CricketDetail Page", true);
                int showid = AppSettings.ShowUniqueID;

                if (Constants.connection.Table<ShowList>().Where(i => i.ShowID == showid).FirstOrDefaultAsync().Result != null)
                {
                    if (Constants.connection.Table<ShowList>().Where(i => i.ShowID == showid).FirstOrDefaultAsync().Result.Status != "Custom")
                    {
                        this.ApplicationBar.IsVisible = false;
                        appbarvisible = false;
                    }
                    else
                    {
                        this.ApplicationBar.IsVisible = true;



                    }
                }
                string sharedstatus = Task.Run(async () => await Constants.connection.Table<ShowList>().Where(i => i.ShowID == showid).FirstOrDefaultAsync()).Result.ShareStatus;
                if (sharedstatus == "Shared To Blog")
                    ((ApplicationBarMenuItem)ApplicationBar.MenuItems[0]).Text = "share this" + " " + AppResources.Type + "(" + "Shared)";
                else
                    ((ApplicationBarMenuItem)ApplicationBar.MenuItems[0]).Text = "share this" + " " + AppResources.Type + "(" + "Not Shared)";
                performanceProgressBar.IsIndeterminate = true;

                PageHelper.RemoveEntryFromBackStack("CricketDetail");
                if (NavigationContext.QueryString.TryGetValue("id", out id))
                    AppSettings.ShowID = id;
                if (pvtMainDetails.SelectedIndex == 0)
                {
                    Border frameBorder = (Border)VisualTreeHelper.GetChild(Application.Current.RootVisual, 0);
                    AdRotatorControl Adc = frameBorder.FindName("AdRotatorWin8") as AdRotatorControl;
                    Adc.IsAdRotatorEnabled = false;
                    Adc.Visibility = Visibility.Collapsed;
                }

                tblkVideosTitle.Text = CricketMatch.GetMovieTitle(AppSettings.ShowID);
                performanceProgressBar.IsIndeterminate = false;
                if (appbarvisible == true)
                {
                    if (currentItem.Header != null)
                    {

                        if (currentItem.Header.ToString() == "game")
                        {
                            if (this.ApplicationBar.MenuItems.Count == 2)
                                this.ApplicationBar.MenuItems.RemoveAt(1);

                        }
                        else
                        {
                            if (this.ApplicationBar.MenuItems.Count < 2)
                            {
                                ApplicationBarMenuItem appBarMenuitem = null;
                                if (currentItem.Header.ToString() == "videos")
                                    appBarMenuitem = new ApplicationBarMenuItem("Add videos");
                                else if (currentItem.Header.ToString() == "summary")
                                    appBarMenuitem = new ApplicationBarMenuItem("Add summary");
                                else
                                    appBarMenuitem = new ApplicationBarMenuItem("Add image for cast");
                                appBarMenuitem.Click += btnadd_Click_1;
                                this.ApplicationBar.MenuItems.Add(appBarMenuitem);
                            }
                            else
                            {
                                if (currentItem.Header.ToString() == "videos")
                                    ((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).Text = "Add videos";
                                else if (currentItem.Header.ToString() == "summary")
                                    ((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).Text = "Add summary";
                                else
                                    ((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).Text = "Add image for cast";

                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in PhoneApplicationPage_Loaded Method In CricketDetail.cs file.", ex);
            }

        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {


            try
            {
                int showid = AppSettings.ShowUniqueID;
                if (Task.Run(async () => await Constants.connection.Table<OnlineVideos.Entities.ShowCast>().Where(i => i.ShowID == showid).FirstOrDefaultAsync()).Result == null && Task.Run(async () => await Constants.connection.Table<ShowList>().Where(k => k.ShowID == AppSettings.ShowUniqueID).FirstOrDefaultAsync()).Result.Status == "Custom")
                {
                    pvtMainDetails.Items.Remove(pvtitmcast1);
                    pvtMainDetails.Items.Remove(pvtitmcast2);

                }

                FlurryWP8SDK.Api.LogPageView();
                if (NavigationContext.QueryString.TryGetValue("navigationvalue", out navigationvalue))
                {

                    if (navigationvalue == "1")
                    {
                        if (NavigationContext.QueryString.TryGetValue("pivotindex", out pivotindex))
                            pvtMainDetails.SelectedIndex = Convert.ToInt32(pivotindex);
                        Constants.navigationvalue++;
                    }
                    else
                    {
                        if (NavigationContext.QueryString.TryGetValue("pivotindex", out pivotindex))
                            pvtMainDetails.SelectedIndex = Convert.ToInt32(pivotindex);
                        Constants.navigationvalue--;
                    }
                    while (NavigationService.BackStack.Count() > 1)
                    {
                        if (!NavigationService.BackStack.FirstOrDefault().Source.OriginalString.Contains("CricketDetail"))
                        {
                            NavigationService.RemoveBackEntry();
                        }
                        else
                        {
                            NavigationService.RemoveBackEntry();
                            break;
                        }
                    }
                }
                if (NavigationContext.QueryString.TryGetValue("secondarytileindex", out secondarytileindex))
                    pvtMainDetails.SelectedIndex = Convert.ToInt32(secondarytileindex);
                if (videos.lbxSongsList.IsEnabled == false)
                    videos.lbxSongsList.IsEnabled = true;
                //YouTube.CancelPlay();
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in OnNavigatedTo Method In CricketDetail.cs file.", ex);
            }

        }
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            try
            {
                AppState.searchtitle = "";
                FlurryWP8SDK.Api.EndTimedEvent("CricketDetail Page");
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in OnNavigatedFrom Method In CricketDetail.cs file.", ex);
            }
        }
        protected override void OnBackKeyPress(CancelEventArgs e)
        {

            base.OnBackKeyPress(e);
        }
        private void imgTitle_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }

        private void btnadd_Click_1(object sender, EventArgs e)
        {
            if ((sender as ApplicationBarMenuItem).Text.Contains("cast"))
            {
                Constants.DownloadTimer.Stop();
                NavigationService.Navigate(new Uri("/Views/AddCast.xaml", UriKind.RelativeOrAbsolute));
            }
            else if ((sender as ApplicationBarMenuItem).Text.Contains("summary"))
            {
                Constants.DownloadTimer.Stop();

                NavigationService.Navigate(new Uri("/Views/AddMatchScore.xaml", UriKind.RelativeOrAbsolute));
            }
            else if ((sender as ApplicationBarMenuItem).Text.Contains("videos"))
            {
                Constants.DownloadTimer.Stop();
                Constants.Linkstype = "Songs";
                NavigationService.Navigate(new Uri("/Views/LinksFromOnline.xaml?language=" + string.Empty, UriKind.Relative));
            }
        }

        private void btnshare_Click_1(object sender, EventArgs e)
        {
            try
            {
                if (NetworkHelper.IsNetworkAvailableForDownloads())
                {
                    UploadToBlog upload = new UploadToBlog(AppSettings.ShowUniqueID, page1: this);
                }
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in btnshare_Click_1 Method In Details.cs file.", ex);
            }
        }



        private void pvtitmcast2_LayoutUpdated_1(object sender, EventArgs e)
        {
            if (appbarvisible == true)
            {
                if (currentItem.Header != null)
                {

                    if (currentItem.Header.ToString() == "game")
                    {
                        if (this.ApplicationBar.MenuItems.Count == 2)
                            this.ApplicationBar.MenuItems.RemoveAt(1);

                    }
                    else
                    {
                        if (this.ApplicationBar.MenuItems.Count < 2)
                        {
                            ApplicationBarMenuItem appBarMenuitem = null;
                            if (currentItem.Header.ToString() == "videos")
                                appBarMenuitem = new ApplicationBarMenuItem("Add videos");
                            else if (currentItem.Header.ToString() == "summary")
                                appBarMenuitem = new ApplicationBarMenuItem("Add summary");
                            else
                                appBarMenuitem = new ApplicationBarMenuItem("Add image for cast");
                            appBarMenuitem.Click += btnadd_Click_1;
                            this.ApplicationBar.MenuItems.Add(appBarMenuitem);
                        }
                        else
                        {
                            if (currentItem.Header.ToString() == "videos")
                                ((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).Text = "Add videos";
                            else if (currentItem.Header.ToString() == "summary")
                                ((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).Text = "Add summary";
                            else
                                ((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).Text = "Add image for cast";
                        }
                    }
                }
            }
        }

        private void pvtitmcast1_LayoutUpdated_1(object sender, EventArgs e)
        {
            if (appbarvisible == true)
            {
                if (currentItem.Header != null)
                {

                    if (currentItem.Header.ToString() == "game")
                    {
                        if (this.ApplicationBar.MenuItems.Count == 2)
                            this.ApplicationBar.MenuItems.RemoveAt(1);

                    }
                    else
                    {
                        if (this.ApplicationBar.MenuItems.Count < 2)
                        {
                            ApplicationBarMenuItem appBarMenuitem = null;
                            if (currentItem.Header.ToString() == "videos")
                                appBarMenuitem = new ApplicationBarMenuItem("Add videos");
                            else if (currentItem.Header.ToString() == "summary")
                                appBarMenuitem = new ApplicationBarMenuItem("Add summary");
                            else
                                appBarMenuitem = new ApplicationBarMenuItem("Add image for cast");
                            appBarMenuitem.Click += btnadd_Click_1;
                            this.ApplicationBar.MenuItems.Add(appBarMenuitem);
                        }
                        else
                        {
                            if (currentItem.Header.ToString() == "videos")
                                ((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).Text = "Add videos";
                            else if (currentItem.Header.ToString() == "summary")
                                ((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).Text = "Add summary";
                            else
                                ((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).Text = "Add image for cast";
                        }
                    }
                }
            }
        }
    }
}